package com.cht.commonUtil.infra;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;

public class MSH extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/text");
		response.setCharacterEncoding( SP.UIcodeSet );
		
		String ip = request.getParameter("ip").replace("&nbsp;", "");
		int port = Widgets.getParNumberFromRequest( request.getParameter("port") );
		String empId = request.getParameter("empId");
		String squadId = request.getParameter("squadId");
		String oper = request.getParameter("oper");
		String subsysId = request.getParameter("subsysId");
		String envId = request.getParameter("envId");
		Connection conn = null;
		PreparedStatement ps = null;
		String res = "NOTOK";
		try {
			conn = Widgets.getConn();
			
			if ("add".equalsIgnoreCase(oper)) {
				String sql = "INSERT INTO mpsquadhosts (subsysid,envid,squadid,ip,port,creator,createdDateTime) VALUES(?,?,?,?,?,?,?)";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, envId);
				ps.setString(3, squadId);
				ps.setString(4, ip);
				ps.setInt(5, port);
				ps.setString(6, empId);
				ps.setTimestamp(7, Widgets.cDT());
				ps.execute();
			} else {
				String sql = "DELETE FROM mpsquadhosts WHERE subsysid=? AND envid=? AND squadid=? AND ip=? AND port=?";
				ps = conn.prepareStatement(sql);
				ps.setString(1, subsysId);
				ps.setString(2, envId);
				ps.setString(3, squadId);
				ps.setString(4, ip);
				ps.setInt(5, port);
				ps.execute();
			}
			res = "OK";
			
		} catch(Exception e) {
			Widgets.errLog(e);
		} finally {
			try {
				if ( ps !=null ) { ps.close(); }
				if ( conn !=null ) { conn.close(); }
			} catch (Exception e) { e.printStackTrace(); }
		}
		
		response.getWriter().write(res);
	}

}
